package top.zhaoyuliu.logbook.server.connect.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Semaphore;

import org.springframework.data.mongodb.core.MongoTemplate;

import lombok.extern.slf4j.Slf4j;
import top.zhaoyuliu.logbook.client.builder.LbBuilder;
import top.zhaoyuliu.logbook.server.connect.client.ClientStart;

/**
 * Copyright © 2021 Arain. All rights reserved.
 *
 * @Title: HandlerTrack.java
 * @Prject: logbook-server
 * @Package: top.zhaoyuliu.logbook.server.connect.thread
 * @Description: <功能详细描述>
 * @author: Arain
 * @date: 2021年1月27日 下午1:06:05
 * @version: V1.0
 */
@Slf4j
public class HandlerThread implements Runnable {

	private BlockingQueue<LbBuilder> queue;

	private Integer num;

	private MongoTemplate mongoTemplate;

	private Semaphore semaphore;

	private ClientStart clientStart;

	public HandlerThread(BlockingQueue<LbBuilder> queue, Semaphore semaphore, ClientStart clientStart) {
		super();
		this.queue = queue;
		this.num = clientStart.getLbServiceProperties().getHandlerTaskNum();
		this.mongoTemplate = clientStart.getMongoTemplate();
		this.semaphore = semaphore;
		this.clientStart = clientStart;
	}

	@Override
	public void run() {
		while (true) {
			try {
				List<LbBuilder> list = new ArrayList<>();
				int drainTo = queue.drainTo(list, num);
				if (drainTo <= 0) {
					semaphore.acquire();
				} else {
					clientStart.getTaskNum().addAndGet(-drainTo);
					mongoTemplate.insertAll(list);
				}
			} catch (Throwable e) {
				log.error("", e);
			}
		}
	}

}
